<?php
/**
 * Created by PhpStorm.
 * User: 87976
 * Date: 2018/2/6
 * Time: 11:09
 */

namespace App\Services\Menu;


use App\Repositories\Menu\AdminMenuRepository;

/**
 * Class AdminMenuService
 * @package App\Services\Menu
 */
class AdminMenuService
{

    /**
     * @var AdminMenuRepository
     */
    protected $adminMenuRepository;

    /**
     * @var array
     */
    public static $method = [
        'GET',
        'POST',
        'PATCH',
        'DELETE',
    ];

    /**
     * AdminMenuService constructor.
     * @param AdminMenuRepository $adminMenuRepository
     */
    public function __construct(AdminMenuRepository $adminMenuRepository)
    {
        $this->adminMenuRepository = $adminMenuRepository;
    }


    /**
     * @author Jerry
     * @return mixed
     */
    public function getMenus()
    {
        $menus = $this->adminMenuRepository->findMenus()->toArray();

        $data = self::menusTree($menus);

        return $data;
    }

    /**
     * 获取无限级菜单分类
     * @author Jerry
     * @param array $data
     * @param string $name
     * @param int $parentId
     * @param int $level
     * @return array|bool
     */
    protected static function menusTree(array $data, string $name = 'child', int $parentId = 0, int $level = 0)
    {
        if (empty($data)) {
            return false;
        }

        $arr = [];
        $level += 1;

        foreach ($data as $key => $value) {
            $value['method'] = self::$method[$value['method']];

            if ($value['parent_id'] == $parentId) {

                $child = self::menusTree($data, $name, $value['id'], $level);
                if (! empty($child)) {
                    $value[$name] = $child;
                }

                $arr[] = $value;
            }
        }

        return $arr;
    }

    /**
     * @author Jerry
     * @param array $data
     * @return mixed
     */
    public function insertMenu(array $data)
    {
        return $this->adminMenuRepository->create($data);
    }

    /**
     * @author Jerry
     * @param int $id
     * @return mixed
     */
    public function findMenuById(int $id)
    {
        return $this->adminMenuRepository->find($id);
    }

    /**
     * @author Jerry
     * @param array $data
     * @param int $id
     * @return mixed
     */
    public function updateMenuByMenuId(array $data, int $id)
    {
        return $this->adminMenuRepository->update($data, $id);
    }

    /**
     * @author Jerry
     * @param int $id
     * @return int
     */
    public function deleteMenuByMenuId(int $id)
    {
        return $this->adminMenuRepository->delete($id);
    }
}